<!--
 * @Author: weidewei
 * @Date: 2025-11-04 11:21:16
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-04 16:33:02
 * @Description: 
 * @FilePath: \2025-front-face\review-knowledge\20251104\复习深拷贝.html
-->
<script>
  function deepClone(target, map = new WeakMap()) {
    if (typeof target !== "object" || target === null) return target;
    if (map.get(target)) {
      return map.get(target);
    }
    if (target instanceof Date) return new Date(target.getTime());
    if (target instanceof RegExp) return new RegExp(target);
    if(target instanceof Map) { // Map怎么处理
       const cloneMap = new Map();
       map.set(target,cloneMap); // 一定要先记录映射，再循环
       // 递归拷贝每个键值对
       target.forEach((value,key)=>{
          cloneMap.set(deepClone(key,map),deepClone(value,map));  
       })
       return cloneMap;
    }
    if(target instanceof Set) {
        const cloneSet = new Set();
        map.set(target,cloneSet); // 记录Set的映射
        target.forEach(value=>{
            cloneSet.add(deepClone(value,map));
        });
        return cloneSet;
    }
    let result = Array.isArray(target) ? [] : {};
    map.set(target, result); // 记录「原对象 → 新对象」的映射
    for (let key in target) {
      // if(target.hasOwn)
      result[key] = deepClone(target[key], map); // 传递 map
    }
    return result;
  }
  const obj = {
    a: 111,
    b: 222,
    c: {
      d: {
        e: 333,
      },
    },
    f: new Date(),
  };
  obj.g = obj;
  const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
  const set = new Set([1, 2, 3]);
//   console.log(deepClone(obj));

const map1 = new Map();
map1.set('abcKey','abc');
map1.set(function aKey(){},function a(){})
map1.forEach((a,b)=>{
    console.log(a,b)
})
console.log(map1);

const setDemo = new Set();
const a = {
    name: 'xxx',
    age: 20
}
setDemo.add(a);
console.log('setDemo',setDemo);
a.sex = '男';
console.log('setDemo',setDemo)
setDemo.forEach(a=>{
    console.log('aaaaaaa',a)
})
</script>
